/**
 * 
 */
package com.huateng.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * @author yy
 *
 */
public class ScriptsUtil {
	private static Logger logger = Logger.getLogger(ScriptsUtil.class);

	public static int runScript(String cmdString) throws Exception {
		Process process = Runtime.getRuntime().exec(cmdString);
		printProcessLog(process);
		int exitValue = process.waitFor();
		if (0 != exitValue) {
			logger.error("Run script '" + cmdString + "' failed. error code: " + exitValue);
			throw new Exception("Run script '" + cmdString + "' failed. error code: " + exitValue);
		}
		return exitValue;
	}

	
	private static void printProcessLog(Process process){
		List<String> processList = new ArrayList<String>();
		try {
//			process = Runtime.getRuntime().exec(cmdString);
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = "";
			while ((line = input.readLine()) != null) {
				processList.add(line);
			}
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		for (String line : processList) {
			logger.info(line);
		}
	}
	
	
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
//		String cmdString = "D:/Apache/apache-tomcat-8.0.29/bin/version.bat";
//		String cmdString = "cmd /c dir";
		String cmdString = "cmd /c java -jar D:/Test/ScriptUtil.jar";
		int exitValue = runScript(cmdString);
		logger.info("exitValue: " + exitValue);
	}

}
